#!/usr/bin/env python3
"""
独立的文件选择器脚本
用于在子进程中执行文件选择操作
"""
import sys
import json
import platform
import os
import mimetypes
import argparse

# 预加载tkinter以提升速度
try:
    import tkinter as tk
    from tkinter import filedialog
    TKINTER_AVAILABLE = True
except ImportError:
    TKINTER_AVAILABLE = False

# 修复Windows下tkinter的Tcl/Tk路径问题
if platform.system() == "Windows":
    python_path = sys.executable
    python_dir = os.path.dirname(python_path)
    
    # 查找系统Python安装目录（而不是虚拟环境）
    if ".venv" in python_dir or "venv" in python_dir:
        # 从虚拟环境路径中找到系统Python路径
        parts = python_path.split(os.sep)
        for i, part in enumerate(parts):
            if "Python" in part and part.startswith("Python3"):
                system_python_dir = os.sep.join(parts[:i+1])
                break
        else:
            # 如果找不到，尝试常见的安装路径
            import glob
            possible_paths = [
                r"C:\Users\*\AppData\Local\Programs\Python\Python3*",
                r"C:\Python3*",
                r"C:\Program Files\Python3*"
            ]
            system_python_dir = None
            for pattern in possible_paths:
                matches = glob.glob(pattern)
                if matches:
                    system_python_dir = matches[0]
                    break
    else:
        system_python_dir = python_dir
    
    if system_python_dir:
        tcl_dir = os.path.join(system_python_dir, "tcl")
        if os.path.exists(tcl_dir):
            os.environ["TCL_LIBRARY"] = os.path.join(tcl_dir, "tcl8.6")
            os.environ["TK_LIBRARY"] = os.path.join(tcl_dir, "tk8.6")



def get_file_info(file_path):
    """获取文件详细信息 - 优化版本"""
    try:
        # 快速获取文件基本信息
        file_name = os.path.basename(file_path)
        name_without_ext, file_extension = os.path.splitext(file_name)
        
        # 快速获取文件大小
        file_size = os.path.getsize(file_path)
        
        # 简化MIME类型获取，只基于扩展名
        mime_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
        
        return {
            "type": mime_type,
            "name": file_name,
            "size": file_size,
            "local": file_path,
            "extName": name_without_ext
        }
    except Exception:
        return None


def setup_root_window():
    """设置根窗口 - 优化版本（保持跨平台兼容）"""
    root = tk.Tk()
    root.withdraw()  # 隐藏根窗口
    
    # 跨平台的前台显示设置
    platform_name = platform.system()
    if platform_name == "Darwin":  # macOS
        root.lift()
        root.attributes('-topmost', True)
    elif platform_name == "Windows":  # Windows
        root.wm_attributes('-topmost', 1)
    else:  # Linux等
        root.attributes('-topmost', True)
    
    return root


def build_filetypes(file_types):
    """构建文件类型过滤器 - 只支持自定义过滤器格式"""
    filetypes = []
    if file_types and isinstance(file_types, list):
        for filter_obj in file_types:
            if isinstance(filter_obj, dict) and 'name' in filter_obj and 'ext' in filter_obj:
                name = filter_obj.get('name', '支持的文件')
                extensions = filter_obj.get('ext', [])
                if extensions:
                    ext_patterns = []
                    for ext in extensions:
                        if ext.startswith('.'):
                            ext_patterns.append("*" + ext)
                    if ext_patterns:
                        filetypes.append((name, ";".join(ext_patterns)))
    
    filetypes.append(("所有文件", "*.*"))
    return filetypes


def select_files_dialog(multiple, file_types, title):
    """打开文件选择对话框 - 优化版本（使用预加载模块）"""
    if not TKINTER_AVAILABLE:
        raise Exception("tkinter不可用")
    
    try:
        root = setup_root_window()
        filetypes = build_filetypes(file_types)
        
        try:
            # 使用预加载的filedialog，减少导入开销
            dialog_func = filedialog.askopenfilenames if multiple else filedialog.askopenfilename
            result = dialog_func(
                parent=root,
                title=title,
                filetypes=filetypes
            )
            
            # 统一处理返回结果
            if multiple:
                file_paths = list(result) if result else []
            else:
                file_paths = [result] if result else []
                
            return file_paths
            
        finally:
            root.destroy()
                
    except Exception as e:
        raise Exception(f"tkinter错误: {str(e)}")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='文件选择器')
    parser.add_argument('--multiple', action='store_true', help='多选模式')
    parser.add_argument('--file-types-json', help='JSON格式的文件类型过滤器')
    parser.add_argument('--stdin', action='store_true', help='从标准输入读取JSON')
    parser.add_argument('--title', default='选择文件', help='对话框标题')
    
    args = parser.parse_args()
    
    try:
        # 处理文件类型参数
        file_types = []
        if args.stdin:
            # 从标准输入读取JSON
            import sys
            input_data = sys.stdin.read().strip()
            if input_data:
                file_types = json.loads(input_data)
        elif args.file_types_json:
            file_types = json.loads(args.file_types_json)
        
        # 执行文件选择
        file_paths = select_files_dialog(
            multiple=args.multiple,
            file_types=file_types,
            title=args.title
        )
        
        # 处理结果
        if not file_paths:
            result = {"files": [], "cancelled": True}
        else:
            result_files = []
            for file_path in file_paths:
                file_info = get_file_info(file_path)
                if file_info:
                    result_files.append(file_info)
            
            result = {"files": result_files, "cancelled": False}
        
        print(json.dumps(result, ensure_ascii=False))
        
    except Exception as e:
        error_result = {"error": str(e)}
        print(json.dumps(error_result, ensure_ascii=False))


if __name__ == "__main__":
    main() 